package com.xy.work.template.base.utils;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xy.work.template.base.interceptor.LoginInterceptor;
import com.xy.work.template.base.domain.LoginUser;
import com.xy.work.template.common.constant.Constants;
import com.xy.work.template.common.enums.CommonCodeEnum;
import com.xy.work.template.common.exception.BaseCustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.Date;

/**
 * @author niuniu
 * @Date: 2021/5/15 09:03
 * @Description: 常用一些操作
 */
@Slf4j
public class CommonUtil {
    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 得到服务器IP
     * @return
     */
    public static String getHostIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
        }
        return "127.0.0.1";
    }

    /**
     * 得到服务器域名
     * @return
     */
    public static String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
        }
        return "未知";
    }
    /**
     * 获取ip
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals(Constants.LOCALHOST_IP)) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) {
                // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        return ipAddress;
    }
    /**
     * 获取设备标识
     * @param request
     * @return
     */
    public static String getDeviceUnique(HttpServletRequest request) {
        String deviceUnique = null;
        try {
            deviceUnique = request.getHeader("device-unique");
            if(StrUtil.isEmpty(deviceUnique)){
                deviceUnique = request.getHeader("User-Agent");
                if(StrUtil.isEmpty(deviceUnique)){
                    deviceUnique = request.getHeader("user-agent");
                }
                if(StrUtil.isEmpty(deviceUnique)){
                    deviceUnique = request.getHeader("sec-ch-ua");
                }
                deviceUnique=deviceUnique+"-"+getIpAddr(request);
            }
        } catch (Exception e) {
            deviceUnique = "";
        }
        return deviceUnique;
    }


    /**
     * MD5加密
     *
     * @param data
     * @return
     */
    public static String getMd5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(data.getBytes(Constants.UTF8));
            StringBuilder sb = new StringBuilder();
            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
            }

            return sb.toString().toUpperCase();
        } catch (Exception exception) {
        }
        return null;
    }
    /**
     * 响应json数据给前端
     *
     * @param response
     * @param obj
     */
    public static void sendJsonMessage(HttpServletResponse response, Object obj) {
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpStatus.OK.value());
        try (PrintWriter writer = response.getWriter()) {
            writer.print(objectMapper.writeValueAsString(obj));

            response.flushBuffer();

        } catch (IOException e) {
            log.warn("响应json数据给前端异常",e);
        }
    }

    /**
     * 得到当前用户登陆对象信息
     * @return
     */
    public static LoginUser getCurrentLoginUser() {
        return LoginInterceptor.threadLocal.get();
    }

    /**
     * 得到当前检测过用户登陆对象信息
     * @return
     */
    public static LoginUser getCheckCurrentLoginUser(){
        LoginUser  loginUser=getCurrentLoginUser();
        if(ObjectUtil.isNull(loginUser)){
            throw new BaseCustomException(CommonCodeEnum.LOGIN_EXPIRE);
        }
        return loginUser;
    }

}
